﻿namespace PAR.Audio
{
    using System;
    using Microsoft.Xna.Framework.Audio;
    using NAudio.Wave;

    public class PhoneWaveIn : IWaveIn
    {
        readonly Microphone _mic;
        byte[] _buffer; 

        public PhoneWaveIn()
        {
            _mic = Microphone.Default;
        }

        public void StartRecording()
        {
            _mic.BufferDuration = TimeSpan.FromSeconds(1); 
            _buffer = new byte[_mic.GetSampleSizeInBytes(_mic.BufferDuration)];
            _mic.BufferReady += _mic_BufferReady;
            _mic.Start();
        }

        void _mic_BufferReady(object sender, EventArgs e)
        {
            _mic.GetData(_buffer);

            if (DataAvailable != null)
                DataAvailable(this, new WaveInEventArgs(_buffer, _buffer.Length));
        }

        public void StopRecording()
        {
            _mic.Stop();
            _mic.BufferReady -= _mic_BufferReady;
        }

        public event EventHandler<WaveInEventArgs> DataAvailable;

        public void Dispose()
        {
            if (_mic.State == MicrophoneState.Started)
            {
                StopRecording();
            }
        }
    }
}
